import sys
import socket
import threading
from common import utils 
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *

from ui.Ui_my_main_window import Ui_MainWindow




class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        self.ui = Ui_MainWindow()
        #加载ui内容
        self.ui.setupUi(self)#self  
        
        self.tcp_client:socket.socket = None
        
        self.init_ui()
    
    def run_tcp_client(self,target_ip,target_port):
         #创建socket对象
        self.tcp_client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        #连接服务器
        try:
            self.tcp_client.connect((target_ip,int(target_port)))
            print("服务器连接成功")
        except Exception as e:
            print("服务器连接失败",e)
            self.tcp_client = None
            return 
        
        
        self.ui.btn_connect.setIcon(QIcon(":/ic/连接 (1).png"))
        self.ui.btn_connect.setText("断开连接")
        
        
        local_ip,local_port = self.tcp_client.getsockname()
        print(f"本地ip:{local_ip},本地端口:{local_port}")
        
 
        while True:
             #阻塞 
            bytes_data = self.tcp_client.recv(1024)
            if bytes_data:
                msg = utils.decode_data(bytes_data)
                print(f"收到消息:{msg}")
            else:
                print("服务器断开连接")
                break
        self.tcp_client.close()
        self.tcp_client = None  
        
           
    @pyqtSlot()    
    def on_btn_connect_clicked(self):#点击连接
        #1.获取用户输入的ip和端口
        mode = self.ui.cb_mode.currentText()
        target_ip = self.ui.edit_target_ip.text()
        target_port = self.ui.edit_target_port.text()
        print(f"mode:{mode},ip:{target_ip},port:{target_port}")
        #2.线创建子线程，运行socket数据接收任务
        ti = threading.Thread(target=self.run_tcp_client,
                              args=(target_ip,target_port),
                              daemon=True)
        ti.start()
       
    @pyqtSlot()     
    def on_btn_send_clicked(self):#点击发送
        text = self.ui.edit_send.toPlainText()#
        if len(text)==0:
            self.statusBar().showMessage("请先输入内容，再发送",1000)
            return 
        if self.tcp_client is None:
            self.statusBar().showMessage("请连接服务器，再发送！",1000)
            QMessageBox.warning(self,"发送失败","请先连接服务器再发送")#生成提示框
            return
        self.tcp_client.send(text.encode())
        
    def init_ui(self):
        self.ui.edit_target_ip.setText("127.0.0.1")
        self.ui.edit_target_port.setText("8080")
        pass
        # self.ui.btn_connect.clicked.connect(self.on_connect_clicked)
        
if __name__ == '__main__':
    app = QApplication(sys.argv)
    mywindow = MainWindow()
    mywindow.show()
    sys.exit(app.exec_())